package com.lanhai.mind.dispatch;

import com.lanhai.mind.beans.AgvBean;
import com.lanhai.mind.beans.DeviceDataBean;
import com.lanhai.mind.dao.DeviceDao;
import com.lanhai.mind.interfaces.IAgv; 
import com.lanhai.mind.interfaces.IAgvEvent;
import com.lanhai.mind.interfaces.IAgvMount;
import com.lanhai.mind.interfaces.IDevice; 
import com.lanhai.mind.interfaces.IDeviceMount;
import com.lanhai.mind.interfaces.IDeviceProtocol;
import com.lanhai.mind.interfaces.IDot;
import com.lanhai.mind.utils.DataSendTools;

/**
 * 设备的处理
 * 
 * @author zhengwei
 *
 */
public class DispatchDevice {
	IDevice iDevice;
	IDot iDot;
	IAgv iAgv;
	IAgvEvent iAgvEvent; 
	IAgvMount iAgvMount; 
	IDeviceMount iDeviceMount;

	public void resolve(DeviceDataBean bean) {

		// 获取真实的设备
		IDeviceProtocol device = iDevice.getRealDevice(bean.getIp());
		if (device == null)
			return;

		// 获取点位
		DeviceDao deviceDao = iDevice.getDao(bean.getIp(), bean.getPort(), bean.getLine());
		if (deviceDao == null) {
			return;
		}
		switch (bean.getEventType()) {
		case AllowLeave:
			// 通知小车离开
			AgvBean agv = iAgv.getBeanByDotNo(deviceDao.getDotNO());
			if (agv != null) {

				// 回退主路
				iAgvEvent.toRoad(agv,  0);
				// 清理小车的装载情况
				iAgvMount.clear(agv.getAgvId());
			}
			
			//机台不再传输
			iDeviceMount.setTransing(deviceDao.getDeviceid(),false); 
			
			// 对接设备清零
			DataSendTools.sendData(deviceDao.getIp(), deviceDao.getPort(), device.clear(bean.getLine()));
			break;
		case AllowTrans:
			 //允许传输
			AgvBean agv2 = iAgv.getBeanByDotNo(deviceDao.getDotNO());
			if(agv2!=null) {
				switch (agv2.getCurrentTrans()) {
				case DownIn:
					iAgvEvent.transDown(agv2, true);
					break;
				case DownOut:
					iAgvEvent.transDown(agv2, false);
					break; 
				case UpIn:
					iAgvEvent.transUp(agv2, true);
					break;
				case UpOut:
					iAgvEvent.transUp(agv2, false);
					break;
				case UpInAndDownOut:
					iAgvEvent.transUpInAndDownOut(agv2);
					break;
				
				case UpOutAndDownIn:
					iAgvEvent.transUpOutAndDownIn(agv2);
					break;
				default:
					//nothing
					break; 
				}
			}
			break;

		case Info: 
			// 更新装卸情况
			if(iDeviceMount.isTransing(deviceDao.getDeviceid())==false){
				iDeviceMount.saveCache(deviceDao.getDeviceid(), bean.getBean());
			} 
			break;
		case Error:
			iDeviceMount.setTransing(deviceDao.getDeviceid(),false); 
			break;
		default:
			break;
		}

	}
}
